<template>
  <div class="app-container">
    <div style="text-align: right">
      <el-button @click="onCancel">返回</el-button>
    </div>
<!--    <el-card class="box-card" style="margin-top: 20px">-->
<!--      <div slot="header" class="clearfix">-->
<!--        <span>基本信息</span>-->
<!--      </div>-->
<!--      <el-descriptions :column="2">-->
<!--        <el-descriptions-item label="单据编号">{{info.orderCode}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="需求日期">{{info.workTime}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="填写人员">{{info.businessFillingName}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="所在部门">{{info.deptName}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="填写日期">{{info.fillingTime}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="备注">{{info.remark}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="审核状态">-->
<!--          <span v-if="info.auditResult === 0">待提交</span>-->
<!--          <span v-else-if="info.auditResult === 1">待审核</span>-->
<!--          <span v-else-if="info.auditResult === 2">审核通过</span>-->
<!--          <span v-else-if="info.auditResult === 3">审核拒绝</span>-->
<!--          <span v-else-if="info.auditResult === 4">审核中</span>-->
<!--          <span v-else>{{info.auditResult}}</span>-->
<!--        </el-descriptions-item>-->
<!--&lt;!&ndash;        <el-descriptions-item label="审核部门">{{info.auditDeptName}}</el-descriptions-item>&ndash;&gt;-->
<!--&lt;!&ndash;        <el-descriptions-item label="当前审核人">{{info.auditNmae}}</el-descriptions-item>&ndash;&gt;-->
<!--&lt;!&ndash;        <el-descriptions-item label="审核时间">{{info.auditTime}}</el-descriptions-item>&ndash;&gt;-->
<!--&lt;!&ndash;        <el-descriptions-item label="待审核人员">{{info.auditNmae}}</el-descriptions-item>&ndash;&gt;-->
<!--      </el-descriptions>-->
<!--    </el-card>-->

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>用工需求预测</span>
      </div>
      <el-descriptions :column="3" size="medium">
        <el-descriptions-item label="单据编号">{{info.orderCode}}</el-descriptions-item>
        <el-descriptions-item label="需求日期">{{info.workTime}}</el-descriptions-item>
        <el-descriptions-item label="填写人员">{{info.businessFillingName}}</el-descriptions-item>
        <el-descriptions-item label="所在部门">{{info.deptName}}</el-descriptions-item>
<!--        <el-descriptions-item label="填写日期">{{info.fillingTime}}</el-descriptions-item>-->
        <el-descriptions-item label="备注">{{info.remark}}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <span v-if="info.auditResult === 0">待提交</span>
          <span v-else-if="info.auditResult === 1">待审核</span>
          <span v-else-if="info.auditResult === 2">审核通过</span>
          <span v-else-if="info.auditResult === 3">审核拒绝</span>
          <span v-else-if="info.auditResult === 4">审核中</span>
          <span v-else>{{info.auditResult}}</span>
        </el-descriptions-item>

        <el-descriptions-item label="用工日期">{{info.workTime}}</el-descriptions-item>
        <el-descriptions-item label="班组">{{info.workGroupName}}</el-descriptions-item>
        <el-descriptions-item label="班次">{{info.shiftTimeName}}</el-descriptions-item>
<!--        <el-descriptions-item label="预估业务量">{{info.predictNumber}}</el-descriptions-item>-->
        <el-descriptions-item label="业务总量">{{info.predictNumber}}万件</el-descriptions-item>
        <el-descriptions-item label="测预24h">{{info.future24PredictNumber}}万件</el-descriptions-item>
        <el-descriptions-item label="测预12h">{{info.future12PredictNumber}}万件</el-descriptions-item>
        <el-descriptions-item label="省内未发">{{info.provinceNotIssued}}万件</el-descriptions-item>
        <el-descriptions-item label="车辆数">{{info.carNumber}}</el-descriptions-item>
        <el-descriptions-item label="待卸量">{{info.unloadedNumber}}万件</el-descriptions-item>
        <el-descriptions-item label="班组遗留">{{info.bequeath}}万件</el-descriptions-item>

        <el-descriptions-item label="启用方案">{{info.enableSchemeName}}</el-descriptions-item>
        <el-descriptions-item label="业务量分档">{{info.businessClassification}}万件</el-descriptions-item>
        <el-descriptions-item label="标准人数">{{info.standardNumber}}</el-descriptions-item>
        <el-descriptions-item label="预估用工量">{{info.estimatedLaborNum}}</el-descriptions-item>
        <el-descriptions-item label="标准人效比">{{info.standardRatio}}</el-descriptions-item>
        <el-descriptions-item label="预估人效比">{{info.estimateRatio}}</el-descriptions-item>
        <el-descriptions-item label="控制百分比">{{info.controlRatio}}%</el-descriptions-item>
        <el-descriptions-item label="预估百分比">{{info.estimatedArrivalRatio}}%</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>人员配置</span>
      </div>
      <el-table
        :data="staffData"
        :span-method="objectSpanMethod"
        border
        size="mini"
        :summary-method="getSummaries"
        show-summary
        style="width: 100%">
        <el-table-column
          prop="regionName"
          label="区域"
          width="180">
        </el-table-column>
        <el-table-column
          prop="groupName"
          label="组别">
        </el-table-column>
        <el-table-column
          prop="groupNumber"
          align="center"
          label="组别人数">
        </el-table-column>
        <el-table-column
          prop="postName"
          label="岗位">
        </el-table-column>
        <el-table-column
          prop="quota"
          align="center"
          label="定额">
        </el-table-column>
        <el-table-column
          prop="regionNumber"
          align="center"
          label="区域人数">
        </el-table-column>
      </el-table>

      <el-alert
        v-if="warning"
        :title="'汇总人数超过预估人数的'+warningRate+'%！'"
        :closable="false"
        show-icon
        type="warning">
      </el-alert>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>设备配置</span>
      </div>
      <div class="device-wrap">
        <div style="margin-top: 10px">
          <span class="itemStatus">启用</span>
          <span class="itemStatus red">停用</span>
        </div>
        <el-table
          v-if="deviceData.length"
          :data="deviceData"
          border
          style="width: 100%;margin-top: 20px">
          <el-table-column
            prop="equipmentName"
            label="作业时间"
            width="180">
          </el-table-column>
          <el-table-column
            v-for="item in deviceTime"
            :prop="`${item}`"
            :label="`${item}`">
            <template slot-scope="scope">
              <div class="status" :class="{green:scope.row[item] == 1,red:scope.row[item] == 0}"></div>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>附件</span>
      </div>
      <div style="max-width: 500px">
        <div v-for="(item,index) in fileList">
<!--          {{index+1}}、<el-link type="primary" target="_blank" :href="item"><i class="el-icon-link"></i>附件{{index+1}}</el-link>-->
          {{index+1}}、<el-link type="primary" @click="handleAnnex(item.fileName)"><i class="el-icon-link"></i>{{item.name}}</el-link>
        </div>
      </div>

    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>审核记录</span>
      </div>
      <el-table
        :data="auditLogs"
        border
        style="width: 100%">
        <el-table-column
          prop="auditResult"
          label="审核结果">
          <template slot-scope="scope">
            <span v-if="scope.row.auditResult === 0">待提交</span>
            <span v-else-if="scope.row.auditResult === 1">待审核</span>
            <span v-else-if="scope.row.auditResult === 2">审核通过</span>
            <span v-else-if="scope.row.auditResult === 3">审核拒绝</span>
            <span v-else-if="scope.row.auditResult === 4">审核中</span>
            <span v-else>{{scope.row.auditResult}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditName"
          label="审核人员">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="批注">
        </el-table-column>
        <el-table-column
          prop="auditDeptName"
          label="审核部门">
        </el-table-column>
        <el-table-column
          prop="auditTime"
          label="审核时间">
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>

<script>
  import {getOperationalDetail, getSchemeConfigAndStrategy} from "@/api/operation";
  export default {
    data(){
      return {
        info: {},  //基本信息
        staffData: [], //人员配置数据
        deviceData: [], //设备配置数据
        deviceTime: [], //设备工作时间
        fileList: [],  //附件
        auditLogs: [],  //附件
        // 预警额度
        warningRate: '',
        //汇总人数超出预警
        warning: false,

      }
    },
    created(){
      const params = this.$route.query;
      if(params){
        this.getOperationalDetail(params)
      }
    },
    computed: {
      areaNum(){  //获取区域数组
        return new Set(this.staffData.map(o => o.regionName));
      },
      groupNum(){  //获取组别数组
        return new Set(this.staffData.map(o => o.groupName));
      }
    },
    methods: {
      /** 下载附件操作 */
      handleAnnex(fileName) {
        // console.log(fileName)
        window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(fileName) + "&delete=" + false;
      },
      onCancel() {
        this.$router.replace({path:"/operationManagement/need/list"});
      },
      getOperationalDetail(params){
        getOperationalDetail(params).then(res => {
          console.log(res)
          if(res.code === 200){
            const data = res.data || {};
            this.info = data.baseData || {};
            this.staffData = data.deps;
            const deviceData = this.convertDeviceData(data.equipments)
            this.deviceData = deviceData;

            const fileList = [];
            const urls = data.urls || [];
            urls.forEach((item,index)=>{
              const num = index+1;
              // const name = item.substring(item.lastIndexOf("/")+1);
              const obj = {
                name: "附件"+num,
                fileName: item,
                url: item
              };
              fileList.push(obj)
            })
            this.fileList = fileList;
            this.auditLogs = data.auditLogs;

            //根据方案id 人员配置以及超限策略获取
            this.getSchemeConfigAndStrategy(data.baseData.enableSchemeId)
          }
        })
      },
      //人员配置以及超限策略获取
      getSchemeConfigAndStrategy(id){
        getSchemeConfigAndStrategy(id).then(res=>{
          console.log(res)
          const data = res.data || {};
          //超限策略
          if(data.strategyCx){
            this.warningRate = data.strategyCx;
            //汇总人数预警
            this.warningStatus()
          }
        })
      },
      warningStatus(){  //汇总人数预警
        const quota = this.getQuotaSum();
        const total = this.getAreaSum();
        // console.log(quota,total)
        const rate = (total-quota)/quota*100;
        if(this.warningRate && quota && total && rate > this.warningRate){
          this.warning = true
        }else {
          this.warning = false
        }

        // const warningRate = this.warningRate;
        // if(warningRate){
        //   //合理人数
        //   const form = this.info;
        //   const rational = (form.standardNumber / form.businessClassification)*form.predictNumber*(1+warningRate/100);
        //   // const quota = this.getQuotaSum();
        //   const total = this.getAreaSum();
        //   // console.log(quota,total)
        //   const rate = (total-rational)/rational*100;
        //   if( rational && total && rate >= warningRate){
        //     this.warning = true
        //   }else {
        //     this.warning = false
        //   }
        // }else {
        //   this.warning = false
        // }

      },
      //定额合计
      getQuotaSum(){
        let number = 0;
        this.staffData.forEach(item => {
          if(item.quota){
            number += item.quota;
          }
        });
        return number
      },
      //区域人数合计
      getAreaSum(){
        let number = 0;
        this.staffData.forEach(item => {
          if(item.regionNumber){
            number += item.regionNumber;
          }
        });
        return number
      },
      //格式化设备数据
      convertDeviceData(data){
        const deviceData = []
        const deviceTime = [];
        const beginTime = data[0].beginTime;
        const endTime = data[0].endTime;
        data.forEach((item,index) => {
          if(beginTime>endTime){
            //晚班
            for(let i = beginTime,j=0; i< 24; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
            for(let i = 0,j=0; i< endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }else {
            for(let i = beginTime,j=0; i<= endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }
          deviceData.push(item)
        });
        this.deviceTime = deviceTime;
        return deviceData;
      },
      classGroup(name){  //根据组别名称获取组别数量
        return this.staffData.filter(o => o.groupName == name).length;
      },
      classArea(name){  //根据区域名称获取区域数量
        return this.staffData.filter(o => o.regionName == name).length;
      },
      classGroupLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.groupNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classGroup(tmp[i]);
        }
        return len;
      },
      classAreaLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.areaNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classArea(tmp[i]);
        }
        return len;
      },
      //获取汇总数据
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '汇总人数';
            return;
          }
          const needSum = ["groupNumber","quota","regionNumber"];
          if(needSum.indexOf(column.property) === -1){
            //不需要计算汇总
            return false
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
        });
        return sums;
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        // console.log(row,column,rowIndex,columnIndex)
        if (columnIndex === 0 || columnIndex === 4 || columnIndex === 5) {
          //判断区域rowspan数量
          const len = this.classArea(row.regionName);
          const lenName = this.classAreaLen(row.regionName);
          if (rowIndex === lenName) {   //某区域首位岗位
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某区域非首位岗位
            rowspan: 0,
            colspan: 0
          };
        }else if(columnIndex === 1 || columnIndex === 2 ){
          //判断区域rowspan数量
          const len = this.classGroup(row.groupName);
          const lenName = this.classGroupLen(row.groupName);
          if (rowIndex === lenName) {   //某班级首位学生行
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某班级非首位学生行
            rowspan: 0,
            colspan: 0
          };
        }
      },
    }
  }
</script>
<style>
  .device-wrap .el-table td{
    padding: 0;
  }
  .device-wrap .el-table td .cell{
    padding: 0;
  }
  .device-wrap .el-table td:first-child .cell{
    padding-left: 10px;
  }
</style>
<style scoped>
  .device-wrap .el-table td .status{
    min-height: 36px;
    box-sizing: border-box;
  }
  .device-wrap .el-table td .status.green{
    background-color: green;
  }
  .device-wrap .el-table td .status.red{
    background-color: red;
  }

  .device-wrap .itemStatus{
    padding-left: 40px;
    display: inline-block;
    line-height: 30px;
    position: relative;
    margin-right: 10px;
  }
  .device-wrap .itemStatus::before{
    content: "";
    display: inline-block;
    width: 35px;
    height: 20px;
    position: absolute;
    left: 0;
    top: 5px;
    background-color: green;
  }
  .device-wrap .itemStatus.red::before{
    background-color: red;
  }
</style>
